// popup.js
import api, { login } from "./request.js";

// 配置允许的域名
const ALLOWED_HOSTS = ['jiankang.baidu.com'];

// 显示指定面板
function showPanel(id) {
    document.querySelectorAll('.panel').forEach(el => {
        el.classList.remove('active');
    });
    document.getElementById(id)?.classList.add('active');
}

// 检查当前是否在允许的页面
async function isAllowedDomain() {
    return new Promise((resolve) => {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            const url = tabs[0]?.url;
            if (!url) return resolve(false);
            try {
                const hostname = new URL(url).hostname;
                resolve(ALLOWED_HOSTS.includes(hostname));
            } catch (e) {
                resolve(false);
            }
        });
    });
}

// 获取登录状态
async function getAuthStatus() {
    return new Promise((resolve) => {
        chrome.storage.local.get(['isLoggedIn', 'authToken'], (data) => {
            resolve({
                isLoggedIn: data.isLoggedIn === true,
                token: data.authToken || null
            });
        });
    });
}

// 保存登录状态（✅ 登录成功后在这里存储！）
async function saveAuthStatus(token) {
    return new Promise((resolve) => {
        chrome.storage.local.set({
            isLoggedIn: true,
            authToken: token
        }, () => {
            resolve();
        });
    });
}

// 登出：清除状态
async function logout() {
    return new Promise((resolve) => {
        chrome.storage.local.remove(['isLoggedIn', 'authToken'], () => {
            resolve();
        });
    });
}

// 显示 Token
function displayToken(token) {
    const el = document.getElementById('tokenInfo');
    el.textContent = `Token: ${token ? token.slice(0, 12) + '...' : '未登录'}`;
}

// 监听 storage 变化（替代轮询）
function listenForTokenChange() {
    chrome.storage.onChanged.addListener((changes, namespace) => {
        if (namespace === 'local' && changes.authToken) {
            displayToken(changes.authToken.newValue);
        }
    });
}

// 设置登录事件
function setupLoginEvent() {
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const codeInput = document.getElementById('code');
    const uuidInput = document.getElementById('uuid'); // hidden
    const captchaImg = document.getElementById('captcha-img');
    const statusEl = document.getElementById('loginStatus');

    // 加载验证码
    async function loadCaptcha() {
        try {
            const res = await api.get('/captchaImage');
            if (res.success) {
                captchaImg.src = 'data:image/png;base64,' + res.data.img;
                uuidInput.value = res.data.uuid;
            } else {
                statusEl.textContent = '验证码获取失败';
            }
        } catch (err) {
            console.error('获取验证码失败:', err);
            statusEl.textContent = '网络错误';
        }
    }

    // 初始加载
    loadCaptcha();
    captchaImg.addEventListener('click', loadCaptcha);

    // 登录按钮
    document.getElementById('btnLogin').addEventListener('click', async () => {
        const username = usernameInput.value.trim();
        const password = passwordInput.value.trim();
        const code = codeInput.value.trim();
        const uuid = uuidInput.value.trim();

        if (!username || !password || !code || !uuid) {
            statusEl.textContent = '请填写所有字段';
            statusEl.style.color = 'red';
            return;
        }

        statusEl.textContent = '登录中...';
        statusEl.style.color = '#007acc';

        try {
            const result = await login(username, password, code, uuid);

            if (result.success) {
                // ✅ 登录成功，保存到 storage
                await saveAuthStatus(result.data.token);

                statusEl.textContent = '登录成功！';
                statusEl.style.color = 'green';

                // 切换到主界面
                setTimeout(async () => {
                    const { token } = await getAuthStatus();
                    showPanel('main');
                    setupMainEvent();
                    displayToken(token);
                    listenForTokenChange();
                }, 800);
            } else {
                statusEl.textContent = `登录失败: ${result.error || '未知错误'}`;
                statusEl.style.color = 'red';
                loadCaptcha(); // 刷新验证码
            }
        } catch (err) {
            console.error('请求异常:', err);
            statusEl.textContent = `连接失败: ${err.message.includes('fetch') ? '服务不可达' : err.message}`;
            statusEl.style.color = 'red';
        }
    });
}

// 设置主界面事件
let mainEventBound = false;
function setupMainEvent() {
    if (mainEventBound) return;
    mainEventBound = true;

    document.getElementById('btnStart').addEventListener('click', () => {
        const needGoods = document.getElementById('chkGoods').checked;
        const needEval = document.getElementById('chkEval').checked;

        if (!needGoods && !needEval) {
            document.getElementById('statusText').textContent = '请至少选择一项抓取内容';
            return;
        }

        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            chrome.tabs.sendMessage(tabs[0].id, {
                type: 'START_CRAWL',
                data: { needGoods, needEval }
            });
            document.getElementById('statusText').textContent = '正在抓取...';
        });
    });

    // 登出按钮
    document.getElementById('btnLogout').addEventListener('click', async () => {
        await logout();
        location.reload(); // 重新加载，回到登录页
    });
}

// 初始化
document.addEventListener('DOMContentLoaded', async () => {
    const isAllowed = await isAllowedDomain();

    if (!isAllowed) {
        showPanel('warning');
        return;
    }

    const { isLoggedIn, token } = await getAuthStatus();

    if (!isLoggedIn) {
        showPanel('login');
        setupLoginEvent();
    } else {
        showPanel('main');
        setupMainEvent();
        displayToken(token);
        listenForTokenChange();
    }
});